#!/usr/bin/python
"""
countryUtil.py
*****************************************************
* Copyright 2014, Ty A. Lasky                       *
* Released under the GNU General Public License 3.0 *
* See LICENSE.txt for license information.          *
*****************************************************

Simple utility to read flags.txt and generate countries.txt
Countries.txt will contain lines of form:
	IOC Code, Country, FlagString
for example:
	CAF,Central African Republic,Central-African-Republic

Here, FlagString is such that:
	'http://www.33ff.com/flags/S_flags/flags_of_' + FlagString + '.gif'
yields a fully-qualified URL that gives the corresponding flag image.

The specialCase dictionary contains those countries that can't be automaticaly generated by the simple 
	'-'.join(tokens[2:]

Input file iocCountries.txt is hand copy/paste from:
	http://en.wikipedia.org/wiki/List_of_IOC_country_codes
	(This file should essentially never need to be updated)

TODO: Would be better if can read directly from the wikipedia IOC web site into iocCountries.txt,
or straight to countries.txt

"""

import sys
sys.path.append("../src") # so can find util module
import os
import errno
import util

inUrl = 'http://tylasky.com/res/tennisScore/iocCountries.txt'
directory = '../res'
outFile = directory + '/countries.txt'  # would then need to upload to resource directory on web server

specialCase = {
	'COD':'Congo-DR',
	'FIJ':'Fiji-Islands',
	'GAM':'Gambia',
	'PLE':'Palestinian-Territory',
	'SRB':'Serbia-and-Montenegro',
	'STP':'Sao-Tome-and-Principe',
	'VIN':'Saint-Vincent-and-The-Grenadines'
	}

# make sure output directory exists, and is a directory:
# Following has not been thoroughly tested, e.g. for permissions errors
try:
	os.makedirs(directory)
except OSError as e:
	if e.errno != errno.EEXIST:
		raise

txt = util.getUrlAsString(inUrl)
if not txt is None:
	try:
		fpOut = open(outFile, 'w')
	except IOError as e:
		print(e)
		print("countryUtil: exiting.")
		fpOut.close()
		sys.exit(1)
	for line in util.lineIter(txt):
		line = util.decode(line)
		tokens = line.split()
		if tokens[0] in specialCase: # Special case country, use the hard-coded flag string.
			fpOut.write(tokens[0]+','+' '.join(tokens[2:])+','+specialCase[tokens[0]]+'\n')
		else: # Normal case, just join country words with hyphens
			fpOut.write(tokens[0]+','+' '.join(tokens[2:])+','+'-'.join(tokens[2:])+'\n')
	fpOut.close()
else:
	print("countryUtil: Couldn't open {}, exiting.".format(url))
	sys.exit(1)